unit io_imagecapture_comparator;

{
  This unit defines the TImageComperator class.
}

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Graphics, controls, fgl;

type
  TComparisonImageList = specialize TFPGObjectList<TBitmap>;

  { TImageComperator }

  TImageComperator = class
    private
      FComparisonImageList: TComparisonImageList;
      FNameList: TStringList;
    public
      constructor Create;
      destructor Destroy; override;
    public
      procedure LoadComparisonImage(AFileName: String; AValue: String);
      function CompareImage(AImage: TBitmap): String;
  end;

implementation

{ TImageComperator }

constructor TImageComperator.Create;
begin
  inherited;
  FComparisonImageList := TComparisonImageList.Create;
  FNameList := TStringList.Create;
end;

destructor TImageComperator.Destroy;
begin
  FNameList.Free;
  FComparisonImageList.Free;
  inherited Destroy;
end;

procedure TImageComperator.LoadComparisonImage(AFileName: String; AValue: String);
var
  tmp: TBitmap;
begin
  tmp := TBitmap.Create;
  FComparisonImageList.Add(tmp);
  FNameList.Add(AValue);
  tmp.LoadFromFile(AFileName);
end;

function TImageComperator.CompareImage(AImage: TBitmap): String;
var
  i: integer;
  SmallestDifference : integer;
  CurDifference: integer;
  function difference: integer;
  var
    x,y: integer;
  begin
    result := 0;
    for x := 0 to FComparisonImageList.Items[i].Width do
    begin
      for y := 0 to FComparisonImageList.Items[i].Height do
      begin
        if FComparisonImageList.Items[i].Canvas.Pixels[x,y] <> AImage.Canvas.Pixels[x,y] then
        begin
          inc(result);
        end;
      end;
    end;
  end;
begin
  SmallestDifference := MAXINT;
  for i := 0 to FComparisonImageList.Count-1 do
  begin
    CurDifference := difference;
    if CurDifference < SmallestDifference then
    begin
      result := FNameList.Strings[i];
      SmallestDifference := CurDifference;
    end;
  end;
end;

end.

